package control;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

import main.Res;

public class Button extends Control{
	protected Sprite sprite;
	protected String text;
	protected boolean enable = true;
	
	public Button(Image img, int w, int h,int x,int y) {
		init(img, w, h,x,y,"");
	}
	public Button(Image img, int w, int h,int x,int y,String text) {
		init(img, w, h,x,y,text);
	}
	private void init(Image img, int w, int h,int x,int y,String text)
	{
		sprite = new Sprite(img, w, h);
		sprite.setPosition(x, y);
		this.text = text;
	}
	public void setEnable(boolean enable){
		this.enable = enable;
		if(enable){
			sprite.setFrame(0);
		}else{
			sprite.setFrame(1);
		}
	}
	protected boolean isHover(int x,int y)
	{
		return (x>sprite.getX()
				&&y>sprite.getY()
				&&x<sprite.getX()+sprite.getWidth()
				&&y<sprite.getY()+sprite.getHeight());
	}
	public boolean pointerPressed(int x,int y)
	{
		if(!enable){
			return false;
		}
		if(isHover(x,y))
		{
			sprite.setFrame(1);
			return true;
		}
		sprite.setFrame(0);
		return false;
	}
	
	public boolean pointerReleased(int x,int y)
	{
		if(!enable){
			return false;
		}
		sprite.setFrame(0);
		if(isHover(x,y))
		{
			if(command!= null)
			{
				Res.PlaySound(4);
				command.Do();
			}
			return true;
		}
		return false;
	}
	protected void controlPaint(Graphics g)
	{
		sprite.paint(g);
		g.setFont(fontB);
		g.setColor(0x886600);
		
		g.drawString(text, sprite.getX()+sprite.getWidth()/2+1, sprite.getY()+7,
				Graphics.TOP | Graphics.HCENTER);
		if(enable){
			g.setColor(0xffcc00);
			g.drawString(text, sprite.getX()+sprite.getWidth()/2, sprite.getY()+8,
				Graphics.TOP | Graphics.HCENTER);
		}
	}
}
